﻿using System;
using System.Web;
using System.Web.UI;
using BugTacker.Common;
using BugTracker.BusinessEntities.Entities.Issue;
using BugTracker.BusinessLogic.BTUser;
using BugTracker.BusinessLogic.Issue;
using BugTracker.Core.Infrastructure.Exceptions;
using BugTracker.WebUX.Admin.Modules.AppCode;
using BugTracker.WebUX.WebCode;
using Microsoft.Practices.Unity;

namespace BugTracker.WebUX.Admin.Modules.Issue
{
    public partial class UCIssuePriorityTypeDetail : BTUserControlBase
    {
        #region properties

        private bool IsFileSelected
        {
            get { return (bool?)ViewState["IsFileSelected"] ?? false; }
            set { ViewState["IsFileSelected"] = value; }
        }

        #endregion

        #region load

        protected void Page_Load(object sender, EventArgs e)
        {
            ActionInfoBox.Text = "Ready";
            SetInfoBoxAdding();
            if (!Page.IsPostBack)
            {
                ValidateUrlParam();
            }
            InitButtonPanel();
        }

        #endregion

        #region check url param

        private void ValidateUrlParam()
        {
            string param = Request.QueryString[BTHttpApplication.UrlParam.IMAGE_ID];
            if (!string.IsNullOrEmpty(param))
            {
                int id = 0;
                Int32.TryParse(param, out id);
                if (id != 0)
                {
                    this.Key = id;
                    this.IsEdit = true;
                    SetInfoBoxUpdating();
                    BindData(id);
                }
            }
        }

        #endregion

        #region bind data

        private void BindData(int id)
        {
            try
            {
                var model = Global.IoC.Container.Resolve<IIssuePriorityTypeService>().LoadById(id);
                if (model != null)
                {
                    this.Entity = model;
                    this.NameTextBox.Text = CommonRoutines.Decode(model.Name);
                    this.IsActiveCheckBox.Checked = model.IsActive;
                    BTSession.Image = model.Image;
                    PreviewImage.ImageUrl = BTHttpApplication.AppPaths.FetchSessionImageHandler + "?d=" + Guid.NewGuid().ToString("D");
                }
            }
            catch (BugTrackerExpection e)
            {
                SetInfoBoxError(e.Message);
            }
        }

        #endregion

        #region button panel

        private void InitButtonPanel()
        {
            ButtonPanel.PrepareResources();
            ButtonPanel.Preview.Visible = true;
            ButtonPanel.Submit.Visible = true;
            ButtonPanel.Return.Visible = true;

            ButtonPanel.Preview.Click += PreviewButton_Click;
            ButtonPanel.Submit.Click += SubmitButton_Click;
            ButtonPanel.Return.Click += ReturnButton_Click;

            if (this.IsEdit)
                ButtonPanel.Submit.Text = Resources.Controls.ButtonText_Update;
            else
                ButtonPanel.Submit.Text = Resources.Controls.ButtonText_Save;
        }

        #endregion

        #region infobox

        private void SetInfoBoxFileInvalid()
        {
            ActionInfoBox.Visible = true;
            ActionInfoBox.Text = Resources.Phrases.FileIsInvalid;
            ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.yellow;
        }

        private void SetInfoBoxNoFileSelected()
        {
            ActionInfoBox.Visible = true;
            ActionInfoBox.Text = Resources.Phrases.NoFileSelected;
            ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.yellow;
        }

        private void SetInfoBoxFileHasInvalidLength()
        {
            ActionInfoBox.Visible = true;
            ActionInfoBox.Text = Resources.Phrases.IncorrectFileLength;
            ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.yellow;
        }

        private void SetInfoBoxFileHasIncorrectFormat()
        {
            ActionInfoBox.Visible = true;
            ActionInfoBox.Text = Resources.Phrases.IncorrectFileFormat;
            ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.yellow;
        }

        private void SetInfoBoxAdding()
        {
            MessageInfoBox.Visible = true;
            MessageInfoBox.Text = Resources.Phrases.AddingRecord;
            MessageInfoBox.MessageType = InfoBox.InfoBox.MsgType.green;
        }

        private void SetInfoBoxUpdating()
        {
            MessageInfoBox.Visible = true;
            MessageInfoBox.Text = Resources.Phrases.EditingRecord;
            MessageInfoBox.MessageType = InfoBox.InfoBox.MsgType.green;
        }

        private void SetInfoBoxError(string message)
        {
            ActionInfoBox.Visible = true;
            ActionInfoBox.Text = message;
            ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.red;
        }

        #endregion

        #region validate file

        private bool SessionHasFile()
        {
            return (BTSession.Image == null) ? false : true;
        }

        private bool IsFileLengthValid(HttpPostedFile file)
        {
            return (file.ContentLength > 0) ? true : false;
        }

        private bool IsFileExtensionValid(HttpPostedFile file)
        {
            return CommonRoutines.IsImageFileExtension(file);
        }

        private bool IsFileValid(HttpPostedFile file)
        {
            return (IsFileLengthValid(file) && IsFileExtensionValid(file));
        }

        private void SaveFileToSession(HttpPostedFile file)
        {
            BTSession.PostedFile = file;
        }

        #endregion

        #region view selected image

        private void ViewImage()
        {
            if (ImageFileUpload.HasFile)
            {
                SaveFileToSession(ImageFileUpload.PostedFile);
                if (IsFileValid(ImageFileUpload.PostedFile))
                {
                    byte[] img = CommonRoutines.GetBytesFromPostedFile(ImageFileUpload.PostedFile);
                    byte[] thumb = CommonRoutines.MakeThumb(img, 32, 32);
                    BTSession.Image = thumb;
                    PreviewImage.ImageUrl = BTHttpApplication.AppPaths.FetchSessionImageHandler + "?d=" + Guid.NewGuid().ToString("D");
                    IsFileSelected = true;
                }
                else
                {
                    SetInfoBoxFileInvalid();
                }
            }
            else
            {
                SetInfoBoxNoFileSelected();
            }
        }

        #endregion

        #region saveadding

        private void SaveAdding()
        {
            var model = new IssuePriorityType();
            var guid = Guid.NewGuid();
            model.IssuePriorityTypeID = 0;
            model.Name = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.NameTextBox.Text, 50));
            if (IsFileSelected)
            {
                model.Image = BTSession.Image;
            }
            else
            {
                if (this.ImageFileUpload.HasFile)
                {
                    if (IsFileValid(ImageFileUpload.PostedFile))
                    {
                        byte[] img = CommonRoutines.GetBytesFromPostedFile(ImageFileUpload.PostedFile);
                        byte[] thumb = CommonRoutines.MakeThumb(img, 32, 32);
                        model.Image = thumb;
                        BTSession.Image = thumb;
                        PreviewImage.ImageUrl = BTHttpApplication.AppPaths.FetchSessionImageHandler + "?d=" + Guid.NewGuid().ToString("D");
                    }
                    else
                    {
                        SetInfoBoxFileInvalid();
                    }
                }
                else
                {
                    SetInfoBoxNoFileSelected();
                    return;
                }
            }
            model.IsActive = this.IsActiveCheckBox.Checked;
            model.IsDeleted = false;
            model.RowGuid = guid;
            model.CreatedOn = DateTime.UtcNow;
            model.ModifiedOn = DateTime.UtcNow;

            try
            {
                Global.IoC.Container.Resolve<IIssuePriorityTypeService>().InsertObject(model);
                this.Entity = Global.IoC.Container.Resolve<IIssuePriorityTypeService>().LoadByGuid(guid);

                ActionInfoBox.Text = Resources.Phrases.InsertSuccessful;
                ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.green;

                MessageInfoBox.Text = Resources.Phrases.EditingRecord;
                MessageInfoBox.MessageType = InfoBox.InfoBox.MsgType.blue;

                ButtonPanel.Submit.Text = Resources.Controls.ButtonText_Update;

            }
            catch (BugTrackerExpection e)
            {
                SetInfoBoxError(e.Message);
            }
        }

        #endregion

        #region save editing

        private void SaveEditing()
        {
            var model = (IssuePriorityType)this.Entity;
            model.Name = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.NameTextBox.Text, 50));
            if (this.ImageFileUpload.HasFile)
            {
                if (IsFileValid(ImageFileUpload.PostedFile))
                {
                    byte[] img = CommonRoutines.GetBytesFromPostedFile(ImageFileUpload.PostedFile);
                    byte[] thumb = CommonRoutines.MakeThumb(img, 32, 32);
                    model.Image = thumb;
                    BTSession.Image = thumb;
                    PreviewImage.ImageUrl = BTHttpApplication.AppPaths.FetchSessionImageHandler + "?d=" + Guid.NewGuid().ToString("D");
                }
                else
                {
                    SetInfoBoxFileInvalid();
                }
            }
            else
            {
                model.Image = BTSession.Image;
            }
            model.IsActive = this.IsActiveCheckBox.Checked;
            model.IsDeleted = false;
            model.ModifiedOn = DateTime.UtcNow;

            try
            {
                Global.IoC.Container.Resolve<IIssuePriorityTypeService>().UpdateObject(model);
                this.Entity = Global.IoC.Container.Resolve<IIssuePriorityTypeService>().LoadByGuid(model.RowGuid);

                ActionInfoBox.Text = Resources.Phrases.UpdateSuccessful;
                ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.green;
            }
            catch (BugTrackerExpection e)
            {
                SetInfoBoxError(e.Message);
            }
        }

        #endregion

        #region save

        private void Save()
        {
            if (Page.IsValid)
            {
                if (!IsEdit)
                {
                    SaveAdding();
                }
                else
                {
                    if (this.Entity != null)
                    {
                        SaveEditing();
                    }//should not need else clause
                }
            }
        }

        #endregion

        #region button events

        protected void PreviewButton_Click(object sender, EventArgs e)
        {
            ViewImage();
        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            Save();
        }

        protected void ReturnButton_Click(object sender, EventArgs e)
        {
            Response.Redirect(BTHttpApplication.AppPaths.IssuePriorityTypeList);
        }

        #endregion
    }
}